package com.jin.test.test02;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件夹Image：存放需要合并的图片
 * 文件夹NewImage：存放统一缩放后的图片
 * 文件夹result：程序执行之后的效果
 */
public class CreateImagePdf {
    public static void main(String[] args) {
        try {
            //folderImage：存放需要合并的图片
            String folderImage = "C:\\Users\\Admin\\Desktop\\CreateImagePdf\\Image";
            //folderNewImage：存放统一缩放后的图片
            String folderNewImage = "C:\\Users\\Admin\\Desktop\\CreateImagePdf\\NewImage";
            //folderresult：程序执行之后的效果
            String folderresult = "C:\\Users\\Admin\\Desktop\\CreateImagePdf\\result";
            //缩放图片
            scaleImages(folderImage, folderNewImage);

            // 需要合并的图片文件列表（缩放后的图片）
            File file = new File(folderNewImage);
            File[] files = file.listFiles();
            List<String> imageFiles = new ArrayList<>();
            for (File file1 : files) {
                imageFiles.add(file1.getPath());
            }
            // 合并后的长图文件
            String mergedImageFile = folderresult + "\\mergedImage.jpg";
            //生成一张长图
            mergeImages(imageFiles, mergedImageFile);

            // 生成PDF文件
            String pdfFile = folderresult + "\\mergedImage.pdf";
            createPDF(mergedImageFile, pdfFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 将多个图片文件合并成一张长图
     * @param imageFiles      图片文件列表
     * @param mergedImageFile 合并后的长图文件
     * @throws Exception
     */
    public static void mergeImages(List<String> imageFiles, String mergedImageFile) throws Exception {
        BufferedImage mergedImage = null;
        int heightTotal = 0;
        int maxWidth = 0;
        for (String imageFile : imageFiles) {
            BufferedImage image = ImageIO.read(new File(imageFile));
            //图片大小不保持一致需要把这个判断注释掉，不然会出现黑框
            if (image.getWidth() > maxWidth) {
                maxWidth = image.getWidth();
            }
            heightTotal += image.getHeight();
        }
        mergedImage = new BufferedImage(maxWidth, heightTotal, BufferedImage.TYPE_INT_RGB);
        int offsetY = 0;
        for (String imageFile : imageFiles) {
            BufferedImage image = ImageIO.read(new File(imageFile));
            mergedImage.getGraphics().drawImage(image, 0, offsetY, null);
            offsetY += image.getHeight();
        }
        ImageIO.write(mergedImage, "jpg", new File(mergedImageFile));
    }

    /**
     * 将长图文件转换为PDF文件
     * @param mergedImageFile 长图文件
     * @param pdfFile         PDF文件
     * @throws Exception
     */
    public static void createPDF(String mergedImageFile, String pdfFile) throws Exception {
        //获取下图片的大小，图片的大小就是document的大小（建议图片就是A4纸的大小就行）
        Image image = Image.getInstance(mergedImageFile);
        Rectangle rectangle = new Rectangle(image.getWidth(), image.getHeight());

        Document document = new Document(rectangle, 0, 0, 0, 0);
        // 创建PdfWriter对象
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
        // 打开文档
        document.open();
        // 获取PdfContentByte对象
        PdfContentByte cb = writer.getDirectContent();
        image.scaleToFit(document.getPageSize().getWidth(), document.getPageSize().getHeight());
        // 设置图片位置
        image.setAbsolutePosition(0, 0);
        // 添加图片到PdfContentByte对象
        cb.addImage(image);
        // 关闭文档
        document.close();
    }

    /**
     * 缩放图片方法
     * @param folderImage       存放需要合并的图片
     * @param folderNewImage    存放统一缩放后的图片
     * @throws Exception
     */
    private static void scaleImages(String folderImage, String folderNewImage) throws Exception {
        // 需要合并的图片文件列表
        List<String> imageFiles = new ArrayList<>();
        File file = new File(folderImage);
        File[] files = file.listFiles();

        for (int i = 0; i < files.length; i++) {
            imageFiles.add(files[i].getName());
            System.err.println(files[i].getName());
        }
        for (String imageFile : imageFiles) {
            //加载图片
            File f = new File(folderImage + "\\" + imageFile);
            BufferedImage image = ImageIO.read(f);
            BufferedImage imag = scaleImage(image, 600, 842);
            String[] split = imageFile.split("\\.");
            //保存图片
            File targetFile = new File(folderNewImage + "\\" + split[0] + ".jpg");
            ImageIO.write(imag, "jpg", targetFile);
        }
    }

    /**
     * 等比例缩放图片
     * @param img
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    private static BufferedImage scaleImage(BufferedImage img, int maxWidth, int maxHeight) {
        int width = img.getWidth();
        int height = img.getHeight();

        // 计算缩放比例
        double scale = Math.min((double) maxWidth / width, (double) maxHeight / height);

        // 缩放后的图片宽度和高度
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);

        // 创建缩放后的图片
        BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(img, 0, 0, newWidth, newHeight, null);
        g2d.dispose();

        return scaledImage;
    }
}
